<template>
  <el-row :gutter="20">
    <el-col :span="18">
      <el-card class="select-box">
        <el-menu
          :default-active="activeIndex"
          mode="horizontal"
          @select="handleSelect"
        >
          <el-menu-item index="1">全部</el-menu-item>
          <el-menu-item index="2">推荐</el-menu-item>
          <el-menu-item index="3">圈子</el-menu-item>
        </el-menu>
      </el-card>
      <el-card
        v-loading="loading"
        element-loading-text="Loading..."
        element-loading-background="#fff"
      >
        <div v-show="postList.length === 0" class="lostData-box">
          <img src="@/assets/imgs/lostData.png" alt="" />
          <i>暂无数据</i>
        </div>
        <div
          class="community-box"
          v-for="(item, index) in postList"
          :key="item.postId + '1'"
        >
          <div class="community-content">
            <div class="box-userMessage">
              <el-avatar
                @click.native="toUserArea(item.userId, item.userName)"
                :size="30"
                :src="item.url"
              ></el-avatar>
              <span @click="toUserArea(item.userId, item.userName)">{{
                item.userName
              }}</span>
              <span>{{ item.createTime }}</span>
            </div>
            <div class="box-title" @click="toCommunityDetail(item.postId)">
              {{ item.title }}
            </div>
            <div class="box-message" @click="toCommunityDetail(item.postId)">
              {{ postContent(item.content) }}
            </div>
            <div class="box-img" @click="toCommunityDetail(item.postId)">
              <img :src="randomUrl + '/' + item.postId" alt="" />
            </div>
          </div>
          <div class="box-icon">
            <span class="icon-message" @click="toCommunityDetail(item.postId)">
              <el-icon :size="16"><ChatDotSquare /></el-icon>
              <span>评论</span>
            </span>
            <span
              class="icon-message"
              @click="isLiked(postIsLiked[index], item.postId)"
            >
              <i
                class="iconfont icon-icon"
                :class="postIsLiked[index] ? 'isLiked' : ''"
              ></i>
              <span>{{
                postLikeCount[index] ? postLikeCount[index] : '点赞'
              }}</span>
            </span>
          </div>
        </div>
        <el-pagination
          v-show="postList.length !== 0"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[1, 3, 5, 10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="text-align: center;"
        >
        </el-pagination>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card class="chicken-box">
        <span>心灵文案</span>
        <p>{{ chicken }}</p>
      </el-card>
      <el-card class="ranking-box">
        <span>学习排行榜</span>
        <el-table :data="rankMessage" style="width: 100%" max-height="400px">
          <el-table-column prop="name" label="用户名" align="center">
          </el-table-column>
          <el-table-column prop="clockNum" label="打卡次数" align="center">
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>
    <!-- <el-col :span="6">
      <el-card class="community-message">
        <el-tabs v-model="communityActiveName">
          <el-tab-pane label="社区推荐" name="first">
            <div class="recommend-box" v-for="index in 5" :key="index">
              <img
                src="https://img0.baidu.com/it/u=1697148622,3160789974&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=938"
                alt=""
              />
              <div class="recommend-message">
                <span>高校算法学习社区</span>
                <span>23474成员</span>
              </div>
              <el-button size="mini" type="primary" round>加入</el-button>
            </div>
            <div class="recommend-button">
              <el-button type="primary" size="medium"
                >查看更多<i class="el-icon-arrow-right el-icon--right"></i
              ></el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="我的社区" name="second">
            <div class="myCommunity-box" v-for="index in 5" :key="index">
              <img
                src="https://img0.baidu.com/it/u=1697148622,3160789974&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=938"
                alt=""
              />
              <div class="myCommunity-message">
                <span>高校算法学习社区</span>
              </div>
            </div>
            <div class="recommend-button">
              <el-button type="primary" size="medium"
                >查看更多<i class="el-icon-arrow-right el-icon--right"></i
              ></el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col> -->
  </el-row>
</template>

<script setup lang="ts">
import { useStore } from 'vuex';
import { ref, getCurrentInstance, ComponentInternalInstance, onMounted, computed, onBeforeUnmount } from 'vue';
import { Base64 } from 'js-base64';
import { ElMessage } from 'element-plus';
import { ChatDotSquare } from '@element-plus/icons-vue'


const storeData = useStore();
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 随机图片
const randomUrl = ref('https://source.unsplash.com/random');
// 是否正在加载中
const loading = ref(false);
// 右侧社区栏活跃tab
// const communityActiveName = ref('first'),
// 活跃的index
const activeIndex = ref(proxy.$storage.getItem('activeIndex') || '');
// 当前所在页
const pageNum = ref(1);
// 每页的帖子数
const pageSize = ref(3);
// 帖子总数
const total = ref(0);
// 帖子信息
interface PostList {
  postId: Number
  commentCount: Number
  content: String
  createTime: String
  score: Number
  status: Number
  title: String
  type: Number
  userId: Number
  userName: String
  url: String
};
const postList = ref<PostList[]>([]);
// 获取所有当前页面帖子id
const postIds = ref<Number[]>([]);
// 获取当前页面帖子点赞数以及判断是否已点赞
const postIsLiked = ref<Boolean[]>([]);
const postLikeCount = ref<Number[]>([]);
// 鸡汤
const chicken = ref('');

onMounted(() => {
  loading.value = true;
  getChicken();
  selectPostType();
})

const rankMessage = computed(() => {
  return storeData.state.userSign.rankMessage;
});

// 选择帖子类型
function selectPostType() {
  if (proxy.$storage.getItem('searchKeywords')) {
    getSearchPosts();
  } else if (activeIndex.value === '1') {
    getNormalPosts();
  } else if (activeIndex.value === '2') {
    getInterestPost();
  } else if (activeIndex.value === '3') {
    getRecentPost();
  } else {
    activeIndex.value = '1';
    proxy.$storage.setItem('activeIndex', '1');
    getNormalPosts();
  }
};
// 跳转到社区详情页
function toCommunityDetail(postId: any) {
  const p = Base64.encodeURI(postId);
  proxy.$router.push({
    path: `/communityDetail`,
    query: { p },
  });
};
// 选择帖子类型菜单
function handleSelect(path: any) {
  proxy.$storage.setItem('activeIndex', path);
  proxy.$storage.setItem('searchKeywords', null);
  activeIndex.value = path;
  selectPostType();
};
// 跳转到用户专区
function toUserArea(userId: any, userName: any) {
  // 用户id加密
  const i = Base64.encodeURI(userId);
  // 用户名加密
  const n = Base64.encodeURI(userName);
  proxy.$router.push({
    path: '/contentManage',
    query: { i, n },
  });
};
// 查询帖子信息
function getNormalPosts() {
  loading.value = true;
  proxy.$request.discussPost
    .normalPosts({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    })
    .then((res: any) => {
      if (res.code === '204') {
        loading.value = false;
        postList.value = [];
        return ElMessage({
          message: res.msg,
          type: 'warning',
          duration: 1000,
        });
      }
      postList.value = res.data.list;
      postList.value.forEach((item, index) => {
        if (item.userName === proxy.$storage.getItem('userInfo').userName) {
          item.url = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
        } else {
          item.url = `https://source.unsplash.com/random/${index}`;
        }
      })
      getPostIsLiked();
      total.value = res.data.total;
      loading.value = false;
    });
};
// 查询用户可能感兴趣的帖子
function getInterestPost() {
  loading.value = true;
  proxy.$request.discussPost
    .maybe({
      userId: proxy.$storage.getItem('userInfo').userId,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    })
    .then((res: any) => {
      if (res.code === '204') {
        loading.value = false;
        postList.value = [];
        return ElMessage({
          message: res.msg,
          type: 'warning',
          duration: 1000,
        });
      }
      postList.value = res.data.list;
      postList.value.forEach((item, index) => {
        if (item.userName === proxy.$storage.getItem('userInfo').userName) {
          item.url = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
        } else {
          item.url = `https://source.unsplash.com/random/${index}`;
        }
      })
      getPostIsLiked();
      total.value = res.data.total;
      loading.value = false;
    });
};
// 查询用户关注的近期帖子
function getRecentPost() {
  loading.value = true;
  proxy.$request.discussPost
    .recent({
      userId: proxy.$storage.getItem('userInfo').userId,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    })
    .then((res: any) => {
      if (res.code === '204') {
        loading.value = false;
        postList.value = [];
        return ElMessage({
          message: res.msg,
          type: 'warning',
          duration: 1000,
        });
      }
      postList.value = res.data.list;
      postList.value.forEach((item, index) => {
        if (item.userName === proxy.$storage.getItem('userInfo').userName) {
          item.url = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
        } else {
          item.url = `https://source.unsplash.com/random/${index}`;
        }
      })
      getPostIsLiked();
      total.value = res.data.total;
      loading.value = false;
    });
};
// 把内容的css标签删除
function postContent(content: any) {
  return content.replace(/<[^>]+>|&nbsp;/g, '');
};
// 获取鸡汤
function getChicken() {
  proxy.$request.chicken.getChicken().then((res: any) => {
    chicken.value = res.data;
  });
};
// 获取搜索的帖子信息
function getSearchPosts() {
  loading.value = true;
  proxy.$request.discussPost
    .search(
      { pageNum: 1, pageSize: 3 },
      { keywords: proxy.$storage.getItem('searchKeywords') }
    )
    .then((res: any) => {
      if (res.code === '204') {
        loading.value = false;
        postList.value = [];
        return ElMessage({
          message: res.msg,
          type: 'warning',
          duration: 1000,
        });
      }
      postList.value = res.data.list;
      postList.value.forEach((item, index) => {
        if (item.userName === proxy.$storage.getItem('userInfo').userName) {
          item.url = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
        } else {
          item.url = `https://source.unsplash.com/random/${index}`;
        }
      })
      getPostIsLiked();
      total.value = res.data.total;
      loading.value = false;
    });
};
// 当前页显示帖子个数改变时触发
function handleSizeChange(newPageSize: any) {
  pageSize.value = newPageSize;
  selectPostType();
};
// 页数改变时触发
function handleCurrentChange(newPageNum: any) {
  pageNum.value = newPageNum;
  selectPostType();
};
// 点赞/取消点赞
function isLiked(isLiked: any, postId: any) {
  let action = isLiked ? 0 : 1;
  proxy.$request.like
    .action({
      action: action,
      isLiked: isLiked,
      postId: postId,
      userId: proxy.$storage.getItem('userInfo').userId,
    })
    .then(() => {
      getPostIsLiked();
    });
};
// 获取当前页面帖子点赞数以及判断是否已点赞
function getPostIsLiked() {
  postIds.value = [];
  postList.value.forEach((item) => {
    postIds.value.push(item.postId);
  });
  proxy.$request.like
    .count({
      postIds: postIds.value,
      userId: proxy.$storage.getItem('userInfo').userId,
    })
    .then((res: any) => {
      postIsLiked.value = [];
      postLikeCount.value = [];
      res.data.forEach((item: any) => {
        postIsLiked.value.push(item.isLiked);
        postLikeCount.value.push(item.likeCount);
      });
    });
};

onBeforeUnmount(() => {
  proxy.$storage.setItem('searchKeywords', null);
});
</script>

<style lang="less" scoped>
.select-box {
  margin-bottom: 20px;

  .el-menu.el-menu--horizontal {
    border: none;
    height: 30px;

    .el-menu-item {
      font-size: 18px;
      height: 30px;
      line-height: 30px;
      padding: 0;
      margin: 0 20px;
      background-color: unset;
    }
  }

  .el-menu--horizontal>.el-menu-item.is-active {
    border-bottom: 3px solid #409eff;
  }
}

.lostData-box {
  i {
    display: block;
    margin: -160px 0 50px;
    color: #909399;
    font-size: 20px;
    letter-spacing: 1px;
    font-family: '楷体';
  }
}

.community-box {
  position: relative;

  .community-content {
    text-align: left;

    .box-userMessage {
      height: 40px;
      line-height: 40px;
      margin-bottom: 10px;
      display: inline-block;
      width: 65%;

      .el-avatar {
        float: left;
        margin: 5px;
      }

      span:nth-child(2) {
        display: inline-block;
        color: #606266;
        font-size: 20px;
        margin-left: 5px;

        &:hover {
          cursor: default;
          color: #303133;
        }
      }

      span:nth-child(3) {
        display: inline-block;
        color: #606266;
        font-size: 14px;
        margin-left: 15px;
      }
    }

    .box-title {
      font-weight: 700;
      font-size: 18px;
      margin-bottom: 5px;
      display: inline-block;
      width: 65%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      cursor: default;
    }

    .box-message {
      min-height: 30px;
      font-size: 14px;
      line-height: 30px;
      color: #555666;
      display: inline-block;
      width: 65%;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      cursor: default;

      /deep/ p {
        margin: 0;
      }
    }

    .box-img {
      position: absolute;
      width: 30%;
      height: 140px;
      top: 20px;
      right: 0;
      border-radius: 5px;
      overflow: hidden;

      img{
        height: 100%;
        width: 100%;
        background-size: cover;
      }
    }
  }

  .box-icon {
    height: 40px;
    line-height: 40px;
    margin: 10px 0 20px;
    border-bottom: 1px solid #eee;
    text-align: left;

    .icon-message {
      font-size: 14px;
      color: #999999;
      margin-right: 30px;
      cursor: pointer;
      user-select: none;
      .el-icon{
        float: left;
        margin-top: 13px;
      }

      span {
        margin-left: 5px;
      }
    }

    .icon-message:hover {
      color: #555666;
    }

    .isLiked {
      color: #409eff;
    }
  }
}

.chicken-box,
.ranking-box {
  span {
    display: block;
    margin-bottom: 10px;
    font-weight: 600;
  }
}

.chicken-box {
  margin-bottom: 10px;
  height: 180px;

  p {
    font-family: '宋体';
    padding: 0 11px;
    font-size: 16px;
    color: #e6a23c;
    overflow-wrap: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 6;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}

.ranking-box {
  min-height: 200px;
  max-height: 600px;
  overflow: auto;
}

// .community-message {
//   min-height: 200px;
//   margin-bottom: 20px;

//   .recommend-box {
//     height: 44px;
//     margin-bottom: 15px;

//     img {
//       float: left;
//       height: 44px;
//       width: 44px;
//       margin-right: 10px;
//     }

//     .recommend-message {
//       float: left;
//       width: 120px;

//       span:nth-child(1) {
//         font-size: 14px;
//         color: #222226;
//         white-space: nowrap;
//         overflow: hidden;
//         text-overflow: ellipsis;
//       }

//       span:nth-child(2) {
//         font-size: 12px;
//         color: #555666;
//       }
//     }

//     .el-button {
//       float: right;
//       margin: 8px 0;
//     }
//   }

//   .recommend-button {
//     text-align: center;
//   }

//   .myCommunity-box {
//     margin-bottom: 15px;

//     img {
//       float: left;
//       height: 20px;
//       width: 20px;
//       margin-right: 10px;
//     }

//     .myCommunity-message {
//       font-size: 14px;
//     }
//   }
// }
</style>
